
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
function TreeNode(val, left, right) {
    this.val = (val===undefined ? 0 : val)
    this.left = (left===undefined ? null : left)
    this.right = (right===undefined ? null : right)
}

/**
 * @param {number[]} arr 需要转换的数组
 * @return {TreeNode} 二叉树
 */
function arrToTree (arr) {
    let treeNode = new TreeNode(arr.shift())
    let curArr = [treeNode]
    let netxArr = []
    for (; arr.length > 0 ;) {
        curArr.forEach(e => {
            if (arr[0] === null) {
                arr.shift()
            } else {
                e.left = new TreeNode(arr.shift())
                netxArr.push(e.left)
            }
            if (arr[0] === null) {
                arr.shift()
            } else {
                e.right = new TreeNode(arr.shift())
                netxArr.push(e.right)
            }
        })
        curArr = netxArr
        netxArr = []
    }
    return treeNode
}

/* 
    将题目中的数组（层序遍历）转化成TreeNode格式
    方便调试
    数组为空时不能保证转化的值正确
*/



/**
 * @param {TreeNode} tree 需要转换的二叉树
 * @return {number[]} 数组（后序遍历）
 */
function treeToArr (tree) {
    let arr = []

    function fun(tree) {
        if (tree.val !== undefined) {
            arr.push(tree.val)
        }
        if (tree.left) {
            fun(tree.left)
        }
        if (tree.right) {
            fun(tree.right)
        }
    }

    fun(tree)

    return arr
}